<template>
  <div class="chart-container">
    <div ref="chartRef" style="width: 100%; height: 350px;"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref<HTMLElement>()
let chart: echarts.ECharts | null = null


const xAxisData = ['0-6', '7-12', '13-18', '19-24']
const amountData = [40, 88, 60, 44]
const countData = [50, 40, 40, 25]

onMounted(() => {
  if (chartRef.value) {
    chart = echarts.init(chartRef.value)

    const option = {
      title: {
        text: '时间分布',
        left: '0',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
          color: '#333'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: '{b}<br/>金额: {c0}'
      },
      grid: {
        left: '10%',
        right: '5%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xAxisData,
        axisLine: {
          lineStyle: {
            color: '#DCDFE6'
          }
        },
        axisTick: {
          alignWithLabel: true
        },
        axisLabel: {
          color: '#606266',
          fontSize: 12
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        interval: 20,
        axisLine: {
          lineStyle: {
            color: '#DCDFE6'
          }
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: '#EBEEF5'
          }
        },
        axisLabel: {
          color: '#909399',
          fontSize: 12
        }
      },
      series: [
        {
          name: '金额分布',
          type: 'bar',
          barWidth: '20%',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#2378f7' },
                { offset: 0.7, color: '#2378f7' },
                { offset: 1, color: '#83bff6' }
              ])
            }
          },
          data: amountData,
          label: {
            show: true,
            position: 'top',
            color: '#333'
          }
        }
      ]
    }

    chart.setOption(option)
    window.addEventListener('resize', resizeHandler)
  }
})

const resizeHandler = () => {
  chart?.resize()
}

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeHandler)
  chart?.dispose()
})
</script>

<style scoped>
.chart-container {
  background: #fff;
  border-radius: 8px;
  padding: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
